<template>
  <div class="poster-store-container">
    <div class="swiper-container">
      <span
        v-if="getHostEnvironment() === 'browser' && posterBgList.length > 0"
        style="width:100%;position:absolute;top:50%;margin-top: -63%;text-align:center;font-size:14px;color: #fff;"
        >长按图片，保存至手机，方便分享和再次浏览</span
      >
      <div
        class="swiper-wrapper"
        :class="{ loaded: loaded, 'swiper-no-swiping': !loaded }"
      >
        <div
          v-for="(vItem, index) in posterBgList"
          :key="index"
          class="swiper-slide"
        >
          <!-- top -->
          <div
            v-if="posterBgList.length === 4 && index === 0"
            class="swiper-slide-content-top"
          >
            <div
              :id="`poster-store-type${vItem.idx}`"
              :class="`poster-wrapper wrapper${vItem.idx}`"
            >
              <topThreePosterV2 :shareObj="shareObj" :qrcode="vItem.qrcode" />
            </div>
            <div class="poster-img-wrap">
              <img
                v-show="vItem.posterImgUrl"
                :src="vItem.posterImgUrl"
                class="post-img"
                :class="{ 'no-select': getHostEnvironment() === 'wechat' }"
              />
            </div>
            <div v-show="!vItem.posterImgUrl" class="loading-content">
              <span class="loading-spinner">
                <svg viewBox="25 25 50 50" class="loading-circular">
                  <circle cx="50" cy="50" r="20" fill="none" />
                </svg>
              </span>
            </div>
          </div>
          <!-- 其他3张固定海报 -->
          <div v-else class="swiper-slide-content">
            <div
              :id="`poster-store-type${vItem.idx}`"
              :class="`poster-wrapper wrapper${vItem.idx}`"
            >
              <img class="poster-bg" :src="vItem.bgUrl" alt="图片加载失败" />
              <div :class="`poster-content type${vItem.idx}`">
                <div class="poster-store-name">
                  “&nbsp;<span v-html="shareObj.shopName"></span>
                  &nbsp;”店
                </div>
                <div class="poster-store-qrcode">
                  <img :src="vItem.qrcode" />
                  <img
                    src="@/assets/poster/fingerprint.png"
                    alt="fingerprint"
                  />
                </div>
                <div class="poster-tip">
                  <div class="poster-tip-content">
                    长按二维码分享店铺或保存图片
                  </div>
                </div>
              </div>
            </div>
            <img
              v-show="vItem.posterImgUrl"
              :src="vItem.posterImgUrl"
              class="post-img no-select"
              :class="{ 'no-select': getHostEnvironment() === 'wechat' }"
            />
            <div v-show="!vItem.posterImgUrl" class="loading-content">
              <span class="loading-spinner">
                <svg viewBox="25 25 50 50" class="loading-circular">
                  <circle cx="50" cy="50" r="20" fill="none" />
                </svg>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="poster-operation" @click="hideStorePosterPopupV2">
      <p v-if="getHostEnvironment() !== 'browser'">点击长按可保存图片或分享</p>
      <img src="@/assets/close-btn.png" alt="点击关闭" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode';
import html2canvas from '@/utils/html2canvas.esm';
// import 'swiper/dist/css/swiper.css';
// import Swiper from 'swiper';
import Swiper from '@/views/618/utils/swiper.js';
import '@/views/618/css/swiper.css';
import { getScrollY, getHostEnvironment } from '@/utils/util';
import shareCardMixin from '@/mixins/shareCardMixin';
import topThreePosterV2 from './topThreePosterV2.vue';
import { storePosterInfo } from '@/assets/json/store';

export default {
  components: { topThreePosterV2 },
  mixins: [shareCardMixin],
  data() {
    return {
      shopLogoObj: '',
      activeIndex: 0,
      shareObj: {},
      posterTips: {
        color: '#fff'
      },
      posterBgList: [],
      posterBgList1: [
        {
          bgUrl:
            'https://akmer.aikucun.com/h5_mall/a592ec218bd1e5c64e56fe1703aff05a388fad43_1567760020894_69.png',
          qrcode: '',
          posterImgUrl: '',
          idx: 1
        },
        {
          bgUrl:
            'https://akmer.aikucun.com/h5_mall/47875602e8ed4d73867e294bc8fcb401bb7cf9dc_1567760024304_73.png',
          qrcode: '',
          posterImgUrl: '',
          idx: 2
        },
        {
          bgUrl:
            'https://akmer.aikucun.com/h5_mall/5800dff53d9925d401fe28026dc3806c013d5215_1567760027315_85.png',
          qrcode: '',
          posterImgUrl: '',
          idx: 3
        }
      ],
      loaded: false,
      mi: 0,
      topList: [],
      brandImgList: [],
      productImgList: [],
      timeId: null,
      retryTotal: 0,
      maxRetryTotal: 20 // 最大重试次数
    };
  },
  mounted() {
    this.fetchData();
    this.resetZoom();
  },
  beforeDestroy() {
    this.initData();
  },
  deactivated() {
    this.initData();
  },
  beforeRouteLeave() {
    this.initData();
  },
  methods: {
    getHostEnvironment,
    /* img加载工具方法 */
    loadImg(url) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = url;
        img.onload = () => {
          img.onload = null;
          resolve();
        };
        img.onerror = () => {
          const err = new Error('加载失败');
          reject(err);
        };
      });
    },
    /* 第一步：获取数据 */
    async fetchData() {
      this.$loading.show();
      try {
        // const shareReq = requestShare({ id: 1 });
        // const memberQeq = getUserInfo({ shopId: '' });
        // const shareRes = await shareReq;
        // const memberRes = await memberQeq;
        // if (shareRes.success && shareRes.data && memberRes.success && memberRes.data) {}
        let {
          qrCode,
          forwarder,
          shopName,
          mainPic,
          tagList
        } = storePosterInfo.data;
        this.brandImgList = [mainPic, forwarder.forwarderShopLogoUrl];
        forwarder.forwarderMessage =
          forwarder.forwarderMessage.length > 19
            ? forwarder.forwarderMessage.slice(0, 19) + '...'
            : forwarder.forwarderMessage || '';
        forwarder.forwarderShopName =
          forwarder.forwarderShopName.length > 10
            ? forwarder.forwarderShopName.slice(0, 10) + '...'
            : forwarder.forwarderShopName || '';
        forwarder.forwarderShopDesc =
          forwarder.forwarderShopDesc.length > 12
            ? forwarder.forwarderShopDesc.slice(0, 12) + '...'
            : forwarder.forwarderShopDesc || '';
        shopName =
          shopName.length > 10 ? shopName.slice(0, 10) + '...' : shopName || '';
        this.shareObj = {
          link: qrCode, // qrcode链接
          forwarder, // 转发人信息
          mainPic, // 底图
          shopName,
          tagList
        };
        let arr = [];
        arr.push({
          bgUrl: '',
          qrcode: '',
          posterImgUrl: '',
          idx: 0
        });
        this.posterBgList = arr.concat(this.posterBgList1);
        console.log('==========9.22 大促埋点=============', this.shareObj);
        this.$loading.hide();
        this.init(); // 初始化swiper
      } catch (e) {
        this.$loading.hide();
        this.$toast.fail(e.message || '获取分享信息失败');
      }
    },
    /* 第二步：初始化轮播图 */
    init() {
      const self = this;
      new Swiper('.swiper-container', {
        slideNextClass: 'my-slide-next',
        slidePrevClass: 'my-slide-prev',
        slidesPerView: 1.2,
        spaceBetween: -3,
        centeredSlides: true,
        initialSlide: 0,
        on: {
          slideChange() {
            console.log('this.activeIndex', this.activeIndex);
            self.activeIndex = this.activeIndex;
          }
        },
        pagination: {
          el: '.swiper-pagination',
          clickable: true
        },
        observer: true,
        observeParents: true
      });
      this.loadAllImg();
    },
    /* 第三步：保证图片都loaded */
    async loadAllImg() {
      let imgList = [];
      imgList = imgList.concat(this.brandImgList);
      console.log('==imgList==', imgList);
      const imgsLoadArrays = imgList.map(url => this.loadImg(url));
      // todo 注意 forEach中 await的使用
      // 循环生成二维码
      this.posterBgList.forEach(async (item, index) => {
        item.qrcode = await QRCode.toDataURL(
          `${this.shareObj.link}?mi=${index}`
        );
      });
      this.$nextTick(() => {
        Promise.all(imgsLoadArrays)
          .then(() => {
            try {
              clearInterval(this.timeId);
              this.timeId = setInterval(() => {
                this.retryTotal += 1;
                if (this.retryTotal >= this.maxRetryTotal) {
                  clearInterval(this.timeId);
                  this.retryTotal = 0;
                } else if (this.completeHandle()) {
                  clearInterval(this.timeId);
                  this.retryTotal = 0;
                  this.createQrcode();
                }
              }, 200);
            } catch (err) {
              clearInterval(this.timeId);
              console.error(err);
              this.$toast('海报加载失败，请稍后重试！');
              this.close();
            }
          })
          .catch(err => {
            console.log(err);
            this.$toast('海报加载失败，请稍后重试！');
          });
      });
    },
    /* 第四步：生成海报 */
    async createQrcode() {
      this.posterBgList.forEach(async (item, index) => {
        const curIdx = this.posterBgList.length === 3 ? index + 1 : index;
        item.posterImgUrl = await this.createImg(curIdx);
      });
      console.log('posterBgList===', this.posterBgList);
      /* 不知道为啥直接设置缩放会有偏移，这样可以解决 */
      this.loaded = true;
    },
    createImg(index) {
      return new Promise((resolve, reject) => {
        const source = document.getElementById(`poster-store-type${index}`);
        if (!source) return;
        const rect = source.getBoundingClientRect();

        // 适配iOS 13, 12 及以下 && 安卓
        const scrollY = getScrollY();
        html2canvas(source, {
          allowTaint: true,
          useCORS: true,
          x: rect.left,
          y: rect.top + scrollY,
          scale: 3,
          backgroundColor: 'transparent'
        })
          .then(canvas => {
            const imgUri = canvas.toDataURL();
            resolve(imgUri);
          })
          .catch(err => {
            this.$toast('海报加载失败，请稍后重试！');
            reject(err);
          });
      });
    },
    hideStorePosterPopupV2() {
      this.popupClose();
      this.$emit('hideStorePosterPopupV2');
    },
    completeHandle() {
      const div = document.getElementById('store-poster');
      if (!div) {
        return false;
      }
      const imgArr = div.querySelectorAll('.poster-img') || [];
      return Array.prototype.slice
        .call(imgArr)
        .every(img => img.complete && img.naturalWidth);
    },
    initData() {
      clearInterval(this.timeId);
      this.timeId = null;
      this.retryTotal = 0;
      this.maxRetryTotal = 20;
    }
  }
};
</script>

<style lang="scss" scoped>
.poster-store-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  z-index: 9999;
  .poster-operation {
    position: absolute;
    bottom: 17px;
    left: 50%;
    transform: translate(-50%);
    width: 50%;
    z-index: 888;
    img {
      width: 30px;
      height: 30px;
      margin: 0 auto;
    }
    p {
      font-size: 13px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      line-height: 18px;
      text-align: center;
      margin-bottom: 10px;
    }
  }
  .swiper-container {
    width: 100%;
    height: 100%;
    .swiper-slide {
      display: flex;
      justify-content: center;
      align-items: center;
      .swiper-slide-content-top {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        font-size: 0;
        .loading-content {
          width: 90px;
          min-height: 90px;
          padding: 15px;
          background-color: rgba(50, 50, 51, 0.88);
          border-radius: 5px;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          color: #ffffff;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          .loading-spinner {
            position: relative;
            display: inline-block;
            width: 30px;
            height: 30px;
            vertical-align: middle;
            animation: sd-rotate 0.8s linear infinite;
            margin-bottom: 5px;
          }
          .loading-circular {
            display: block;
            width: 100%;
            height: 100%;
            circle {
              animation: van-circular 1.5s ease-in-out infinite;
              stroke: currentColor;
              stroke-width: 3;
              stroke-linecap: round;
              color: #ffffff;
            }
          }
        }
        @keyframes sd-rotate {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(360deg);
          }
        }
        .poster-wrapper {
          width: 100%;
          height: 100%;
          overflow: hidden;
          position: relative;
          top: -2000px;
        }

        .poster-img-wrap {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;

          .post-img {
            width: 90%;
            border-radius: 10px;
            border: none;
            margin: 16px auto 0;
            &.no-select {
              -webkit-touch-callout: none; /*系统默认菜单被禁用*/
              user-select: none; //文本不能被选择
            }
          }
        }
      }
      .swiper-slide-content {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height: 428px;
        overflow: hidden;
        .loading-content {
          width: 90px;
          min-height: 90px;
          padding: 15px;
          background-color: rgba(50, 50, 51, 0.88);
          border-radius: 5px;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          color: #ffffff;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          .loading-spinner {
            position: relative;
            display: inline-block;
            width: 30px;
            height: 30px;
            vertical-align: middle;
            animation: sd-rotate 0.8s linear infinite;
            margin-bottom: 5px;
          }
          .loading-circular {
            display: block;
            width: 100%;
            height: 100%;
            circle {
              animation: van-circular 1.5s ease-in-out infinite;
              stroke: currentColor;
              stroke-width: 3;
              stroke-linecap: round;
              color: #ffffff;
            }
          }
        }
        @keyframes sd-rotate {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(360deg);
          }
        }
        .poster-wrapper {
          width: 100%;
          height: 100%;
          overflow: hidden;
          position: relative;
          top: -2000px;
          &.wrapper1 {
            background-color: #ff4840;
          }
          &.wrapper2 {
            background-color: #c12725;
          }
          &.wrapper3 {
            background-color: #d65f4f;
          }
          .poster-bg {
            width: 100%;
            height: 428px;
          }
          .icon-double-11 {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 100;
            width: 99px;
            height: 32px;
            img {
              width: 99px;
              height: 32px;
              display: block;
            }
          }
          .poster-content {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            &.type1 {
              .poster-store-name {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 200px;
                left: 0;
                font-size: 14px;
                font-family: PingFang SC;
                font-weight: 500;
                color: rgba(130, 25, 25, 1);
              }
              .poster-store-qrcode {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 280px;
                left: 0;
                img {
                  width: 81px;
                  height: 75px;
                }
              }
              .poster-tip {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 370px;
                left: 0;
                font-size: 10px;
                font-family: PingFang SC;
                font-weight: 400;
                color: rgba(179, 49, 76, 1);
                .poster-tip-content {
                  width: 163px;
                  height: 18px;
                  background: rgba(250, 211, 124, 1);
                  opacity: 0.76;
                  border-radius: 18px;
                  text-align: center;
                  line-height: 18px;
                }
              }
            }
            &.type2 {
              .poster-store-name {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 214px;
                left: 0;
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: normal;
                color: rgba(205, 30, 47, 1);
                span {
                  padding: 0 5px;
                  max-width: 200px;
                  height: 16px;
                  overflow: hidden;
                }
              }
              .poster-store-qrcode {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 230px;
                left: 0;
                img {
                  width: 81px;
                  height: 75px;
                }
              }
              .poster-tip {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 310px;
                font-size: 10px;
                font-family: PingFang SC;
                font-weight: 400;
                color: rgba(205, 30, 47, 1);
              }
            }
            &.type3 {
              .poster-store-name {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                align-items: center;
                top: 120px;
                left: 0;
                font-size: 13px;
                font-family: PingFang SC;
                font-weight: normal;
                color: rgba(85, 85, 85, 1);
                img {
                  width: 5px;
                  height: 5px;
                }
                p {
                  padding: 0 5px;
                  max-width: 180px;
                  height: 16px;
                  overflow: hidden;
                }
              }
              .poster-store-qrcode {
                width: 100%;
                display: flex;
                justify-content: center;
                position: absolute;
                top: 285px;
                left: 0;
                img {
                  width: 81px;
                  height: 75px;
                }
              }
              .poster-tip {
                width: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: 370px;
                font-size: 12px;
                font-family: PingFang SC;
                font-weight: 400;
                color: rgba(205, 30, 47, 1);
                img {
                  width: 7px;
                  height: 7px;
                }
                p {
                  padding: 0 5px;
                }
              }
            }
          }
        }
        .post-img {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          border-radius: 0 10px 10px 10px;
          border: none;
          &.no-select {
            -webkit-touch-callout: none; /*系统默认菜单被禁用*/
            user-select: none; //文本不能被选择
          }
        }
      }
    }
    /* 解决偏移问题 */
    .swiper-wrapper.loaded .swiper-slide:not(.swiper-slide-active) {
      transform: scale(0.9);
    }
  }
}
</style>
